package juc.container;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fangbin
 * @desc 错误的使用ConcurrentHashMap
 * @date 2020/6/19 7:49
 */
public class OperationNotSafe  implements Runnable{
   public static ConcurrentHashMap<String,Integer> concurrentHashMap = new ConcurrentHashMap();
    public static void main(String[] args) throws InterruptedException {
        concurrentHashMap.put("小明",0);
        OperationNotSafe operationNotSafe = new OperationNotSafe();
        Thread t1 = new Thread(operationNotSafe);
        Thread t2 = new Thread(operationNotSafe);
        Thread t3 = new Thread(operationNotSafe);
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        System.out.println(operationNotSafe.concurrentHashMap.get("小明"));

    }

    @Override
    public void run() {
        for(int i=0;i<1000;i++){

            int oldValue = concurrentHashMap.get("小明");
            int newValue = oldValue+1;     //线程不安全

            while (true){
                boolean ret = concurrentHashMap.replace("小明",oldValue,newValue);
                if(ret){
                    break;
                }
            }

        }
    }
}
